//
//  DownloadViewController.swift
//  downloadImage
//
//  Created by Galaxy on 2022/6/20.
//

import UIKit
import SwiftDate
import ReactiveCocoa
import Photos
import WCDBSwift

class DownloadViewController: UIViewController {
    
    @objc private dynamic var logContent:String = ""
    private var isDownloading:Bool = false
    private var pageNum:Int = 1
    public var webSite:WebsiteModel = WebsiteModel(identifier: 0, detailUrl: "", name: "", type: 0)
    var timer:DispatchSourceTimer?
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        timer?.cancel()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        view.backgroundColor = .systemBackground
        let logManager = LogTool.init()
        logManager.makeLogFile()
        logContent = logManager.readLogFile()
        makeUI()
        // 定时器更新文字
        timer = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue.global())
        timer?.schedule(deadline: .now(), repeating: .seconds(1))
        timer?.setEventHandler {
            if self.logContent.count > 2000 {
                self.logContent = String(self.logContent.dropFirst(500))
            }
            DispatchQueue.main.async {
                self.textView.text = self.logContent
                self.textView.scrollRangeToVisible(NSRange(location: self.logContent.count, length: 1))
            }
        }
        timer?.resume()
    }
    
    func makeUI() {
        let bottomBtn = UIButton.init(type: .custom)
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 100, height: 40))
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-10)
        }
        bottomBtn.backgroundColor = .red
        bottomBtn.setTitle("开始", for: .normal)
        bottomBtn.setTitle("暂停", for: .selected)
        bottomBtn.isSelected = false
        bottomBtn.reactive.controlEvents(.touchUpInside).observeValues { button in
            if bottomBtn.isSelected == false {
                // 开始
                self.getListData()
            }else{
                // 暂停
                _ = LogTool.init().saveLog(logContent: self.logContent)
            }
            bottomBtn.isSelected = !bottomBtn.isSelected
            self.isDownloading = !self.isDownloading
        }
    }
    
    lazy var textView: UITextView = {
        let textView = UITextView.init()
        view.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-60)
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
        }
        textView.backgroundColor = .black
        textView.textColor = .white
        textView.isEditable = false
        textView.layoutManager.allowsNonContiguousLayout = false
        return textView
    }()
    
    func getListData() {
        print("当前获取第\(pageNum)页")
        self.logContent += "\n正在获取列表"
        DataManager.init().getListData(website: self.webSite , page: self.pageNum) { listArr in
            // 遍历加载所有的自数据
            print("列表获取成功，共获得\(listArr.count)条数据")
            self.logContent += "\n列表获取成功"
            for item in listArr {
                // 判断某个aritcle是否已经存在
                let model:ArticleModel? = try! FileTool().getDb().getObject(fromTable: "article", where: ArticleModel.Properties.detailUrl == item.detailUrl!)
                if model == nil {
                    self.getDetailData(article: item, isNew: true)
                }else{
                    self.logContent += "\n\(item.detailUrl ?? "")已存在"
                    print("\n\(item.detailUrl ?? "")已存在")
                    if !model!.hasDone {
                        self.getDetailData(article: model!, isNew: false)
                    }
                }
            }
            self.pageNum += 1
            if self.isDownloading {
                self.getListData()
            }
        } failure: { error in
            print(error.localizedDescription)
        }
    }
    
    func getDetailData(article:ArticleModel,isNew:Bool) {
        self.logContent += "\n正在爬取详情\(article.detailUrl ?? "")"
        print("\n正在爬取详情\(article.detailUrl ?? "")")
        DataManager.init().getDetailData(article: article) { imgListArr in
            print("详情获取成功，共获得\(imgListArr.count)张图片")
            self.logContent += "详情获取成功，共获得\(imgListArr.count)张图片"
            // 详情图片获取完毕
            if imgListArr.count > 0 {
                article.hasDone = true
                if isNew {
                    try! FileTool().getDb().insert(article, intoTable: "article")
                } else {
                    try! FileTool().getDb().update(table: "article", on: ArticleModel.Properties.hasDone, with: article, where: ArticleModel.Properties.detailUrl == article.detailUrl!)
                }
                //FIXME: 此处id一直再变
                let articleModel:ArticleModel? = try! FileTool().getDb().getObject(fromTable: "article", where: ArticleModel.Properties.detailUrl == article.detailUrl!)
                for imageItem in imgListArr {
                    self.logContent += "\n获取到图片，图片地址是\(imageItem.imgUrl ?? "")"
                    // 判断该图片是否已经保存
                    let imageModel:ImageModel? = try! FileTool().getDb().getObject( fromTable: "image", where: ImageModel.Properties.imgUrl == imageItem.imgUrl!)
                    if imageModel != nil {
                        self.logContent += "\(imageItem.imgUrl ?? "")已存在，跳过保存"
                        print("\(imageItem.imgUrl ?? "")已存在，跳过保存")
                    } else {
                        // 保存到数据库
                        imageItem.articleId = articleModel?.identifier
                        try! FileTool().getDb().insert(imageItem, on: [ImageModel.Properties.imgUrl,ImageModel.Properties.articleId], intoTable: "image")
                        self.logContent += "\(imageItem.imgUrl ?? "")保存成功,图片父id是\(imageItem.articleId ?? 0)"
                    }
                }
            }else{
                print("获取图片为空，请查找原因。详情地址是\(article.detailUrl ?? "")")
                if isNew == true {
                    try! FileTool().getDb().insert(article, intoTable: "article")
                }
            }
            
        } failure: { error in
            print(error.localizedDescription)
        }
    }
    
    lazy var contentImg: UIImageView = {
        let imgView = UIImageView.init()
        return imgView
    }()
}
